package com.xjl.javacore.code.ioexample.bioexample;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author xiaojinlu1990@163.com
 * @date 2020/1/20 11:37
 */
@Slf4j
public class DemoServer extends Thread {
    private ServerSocket serverSocket;
    public int getPort() {
        return serverSocket.getLocalPort();
    }
    @Override
    public void run() {
        try {
                serverSocket = new ServerSocket(8080);
            while (true) {
                Socket socket = serverSocket.accept();
                RequestHandler requesHandler = new RequestHandler(socket);
                requesHandler.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void main(String[] args) throws IOException {
        DemoServer server = new DemoServer();
        server.start();
     /*   try (Socket client = new Socket(InetAddress.getLocalHost(), server.getPort())) {
            BufferedReader buferedReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
            buferedReader.lines().forEach(s -> System.out.println(s));
        }*/
    }


    class RequestHandler extends Thread {
        //1.建立客户端socket连接，指定服务器位置及端口
        private Socket socket;

        RequestHandler(Socket socket) {
            this.socket = socket;
        }

        @SneakyThrows
        @Override
        public void run() {
                //2.得到socket读写流
                OutputStream os = socket.getOutputStream();
                PrintWriter pw = new PrintWriter(os);
                //输入流
                InputStream is = socket.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
               // log.info(String.valueOf(br.read()));
                //3.利用流按照一定的操作，对socket进行读写操作
                String info = "1111用户名：Tom,用户密码：123456";
                pw.write(info);
                pw.flush();
        }
    }

}
